// var utilAudio = require('utilAudio.js');

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatTime2 = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
}

const formatTime3 = date => {
    const year = parseInt(date.getFullYear().toString().substr(2, 2)).toString(16).toUpperCase()
    const month = (date.getMonth() + 1).toString(16).toUpperCase()
    const day = date.getDate().toString(16).toUpperCase()
    const hour = date.getHours().toString(16).toUpperCase()
    const minute = date.getMinutes().toString(16).toUpperCase()
    const second = date.getSeconds().toString(16).toUpperCase()

    return [year, month, day, hour, minute, second].map(formatNumber).join(' ')
}


const formatDate = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()


    return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}


module.exports = {
    // checkToken: checkToken,

    formatTime: formatTime,
    formatTime2: formatTime2,
    formatTime3: formatTime3,
    formatDate: formatDate,


    initBluetooth: initBluetooth,
    searchBluetooth: searchBluetooth,
    stopBluetoothFond: stopBluetoothFond,
    connToDid: connToDid,

    connectTO: connectTO,
    closeconn: closeconn,

    closeBLEConnection: closeBLEConnection,
    getServices: getServices,
    sendMsg: sendMsg,
    sendHex: sendHex,
    ab2hex: ab2hex,
    ab2Ascii: ab2Ascii,
    ab2String: ab2String,


    readMsg: readMsg,
    onBLEState: onBLEState,
    ctof: ctof,
    ftoc: ftoc,
    handleData: handleData,

    checkbluetooandlocation: checkbluetooandlocation,
    reConn: reConn,
    bindBT: bindBT,
    unbindBT: unbindBT,

    getSn: getSn,


}
var app = getApp()

// ===============蓝牙模块=======================


// 初始化蓝牙适配器
function initBluetooth() {
    //将缓存的设备信息清空
    app.globalData.equs = []
    app.log(app.globalData.equs)


    app.log("===>>初始化蓝牙适配器")
    if (!wx.openBluetoothAdapter) {
        app.log('蓝牙适配器打开失败，请检查微信版本或手机是否支持小程序蓝牙模块！')
    } else {
        app.log("===>>蓝牙适配器打开成功")
        wx.openBluetoothAdapter({
            success: function (res) {
                app.log("===>>获取本机蓝牙适配器状态")
                wx.getBluetoothAdapterState({ //获取本机蓝牙适配器状态
                    success: function (res) {
                        app.log('==>>本机蓝牙适配器状态：')
                        app.log(res)


                        //搜索设备
                        searchBluetooth()

                    }
                })
            },
            fail: function (err) {
                // app.log(err)
                app.log("===>>初始化蓝牙适配器失败")
                wx.showToast({
                    title: '初始化蓝牙适配器失败！',
                    icon: 'none',
                    duration: 3000
                })

            }
        })
    }
}

//搜索获取已发现设备
function searchBluetooth() {
    wx.startBluetoothDevicesDiscovery({ //开始搜寻附近的蓝牙外围设备
        success: function (res) {
            app.log('搜索周边蓝牙设备，==>>搜索成功')
            app.log(res)
            wx.getBluetoothDevices({ //sucess返回uuid 对应的的已连接设备列表，Array类型
                success: function (res) {
                    app.log('===============搜索出来的蓝牙设备列表')
                    app.log(res)
                    //是否有已连接设备
                    wx.getConnectedBluetoothDevices({ ////根据 uuid 获取处于已连接状态的设备
                        success: function (res) {
                            app.log('已连接的蓝牙设备:')
                            app.log(JSON.stringify(res.devices));
                        }
                    })

                    app.log('====>>更新设备信息')

                    updateEqu(res.devices)

                },
                fail(err) {
                    app.log('err==2>>' + err)
                }
            })
        },
        fail(err) {
            app.log('err==1>>' + err)
        }
    })

    //监听寻找到新设备的事件
    wx.onBluetoothDeviceFound(function (res) {
        var devices = res.devices;
        app.log('发现新设备==++++++++')
        getMac(devices[0], function (mac) {
            if (mac != '') {
                devices[0].mac = mac
                let result = app.globalData.equs.some(item => {
                    if (item.deviceId == devices[0].deviceId) {
                        return true
                    }
                })
                if (!result) {
                    //追加设备列表
                    app.globalData.equs.push(devices[0])
                }
            }

        })


        app.log(app.globalData.equs)

        // app.log('==++++++++')

    })

}

function stopBluFund() {
}


function connToDid() {
    let deviceId = app.globalData.equ.deviceId
    app.globalData.ewBluetooth.deviceId = app.globalData.equ.deviceId
    // if (app.globalData.isA) {
    //     app.globalData.ewBluetooth.deviceId = app.globalData.equ.mac
    //
    //     mac = app.globalData.equ.mac
    // }

    app.log('====>>deviceId:' + deviceId)
    connectTO(deviceId, function (res) {
        if (res) {
            app.log('连接设备成功？？' + res)
            app.globalData.equconn0 = true
            stopBluetoothFond()
            // utilAudio.audioPlay(app.globalData.audio.connsucc)

            wx.onBLEConnectionStateChange(function (res) {
                app.log("监听蓝牙连接状态: " + JSON.stringify(res));
                // 该方法回调中可以用于处理连接意外断开等异常情况
                app.log(`设备： ${res.deviceId}  的连接状态: ${res.connected}`)
                if (!res.connected) {
                    app.log('======================>>>>连接已断开')
                    app.globalData.equconn0 = false
                    app.globalData.BLE_SN = 100
                    // utilAudio.audioPlay(app.globalData.audio.connfail)

                }
            })


            getServices(deviceId, function (res) {
                app.log('===========>>>获取服务回调')
                app.log(res)
                onBLEState() //启用notify
                getSn(16)

            })

        } else {
            app.log('连接设备失败')
        }

    })
}

//连接设备
function connectTO(did, callback) {
    // wx.stopBluetoothDevicesDiscovery({ //先停止搜索周边设备
    // 	success: function(res) {
    // 		app.log('连接设备前，先停止搜索周边设备:')
    // 		app.log(res)
    // 	}
    // })
    wx.showLoading({
        title: '连接设备中...',
    })

    wx.createBLEConnection({ //若小程序在之前已有搜索过某个蓝牙设备，并成功建立链接，可直接传入之前搜索获取的deviceId直接尝试连接该设备，无需进行搜索操作。
        deviceId: did,
        timeout: 6000,
        success: function (res) {
            app.log('连接成功:')
            app.log(res)
            wx.hideLoading()


            callback && typeof callback === 'function' ? callback(true) : null;

        },
        fail: function (err) {
            app.log("蓝牙连接调用失败");
            wx.hideLoading()
            app.log(err)


            wx.showToast({
                title: '设备连接失败，重试中...\n若反复如此，请重启小程序或设备',
                icon: 'none',
                duration: 5000
            })

            callback && typeof callback === 'function' ? callback(false) : null;
        },
        complete: function () {
            app.log("==连接的设备ID:" + did);
        }
    })
}

//断开连接
var closeconnnum = 0;


function closeconn(did) {
    if (app.globalData.equconn0) {


        app.log('===>>开始断开连接')
        wx.closeBLEConnection({
            deviceId: did,
            success: function (res) {
                app.log('====>>断开连接成功')
                app.log(res)
                app.globalData.equconn0 = false
                closeconnnum = 0
            },
            fail: function (err) {
                app.log('====>>断开连接失败')
                app.log(err)
                var timeOut = setTimeout(function () {
                    app.log("====>>100")
                    if (closeconnnum < 5) {
                        closeconnnum++
                        closeconn(did)
                    }


                }, 100)

            }
        })
    }
}


//停止搜索蓝牙设备

function stopBluetoothFond() {

    app.log('停止监听蓝牙设备搜索')
    //停止监听蓝牙设备搜索
    wx.offBluetoothDeviceFound()

    app.log('停止搜索周边设备')
    wx.stopBluetoothDevicesDiscovery({ //先停止搜索周边设备
        success: function (res) {
            app.log('扫描结束，停止搜索周边设备:')
            app.log(res)
        }
    })

    closeBLEConnection()


}

function closeBLEConnection() {
    app.log('关闭蓝牙连接')
    wx.closeBLEConnection()
}


//===========字节转换 start=============
function updateEqu(obj) {
    app.log('==更新后的设备信息')

    for (let i in obj) {
        getMac(obj[i], function (mac) {
            if (mac != '') {
                obj[i].mac = mac
                let result = app.globalData.equs.some(item => {
                    if (item.deviceId == obj[i].deviceId) {
                        return true
                    }
                })
                if (!result) {
                    app.globalData.equs.push(obj[i])
                }
            }

        })
    }

    // for (let i = 0; i < obj.length; i++) {
    //     app.globalData.equs[i] = obj[i]
    //     getMac(obj[i], function (mac) {
    //         app.globalData.equs[i].mac = mac
    //     })
    // }
    // let keys = Object.keys(obj);
    // for (let i = 0; i < keys.length; i++) {
    //     let key = keys[i];
    //     app.log(key)
    //     app.globalData.equs[key] = obj[key]
    //
    //
    //     // getMac(obj[key], function (mac) {
    //     //     app.globalData.equs[key][0][0].mac = mac
    //     // })
    // }

    app.log(app.globalData.equs)
}

//===========字节转换 end=============

// 获取连接设备的service服务
function getServices(did, callback) {
    wx.getBLEDeviceServices({ //获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备，包括已经和本机处于连接状态的设备
        // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: did,
        success: function (res) {
            getS_index(res.services)
            app.log('获取蓝牙设备所有服务成功：', res);
            app.log('连接设备的服务：', app.globalData.services);

            app.globalData.ewBluetooth.serviceUuid = res.services[app.globalData.service.s_index].uuid

            app.log("服务uuid:", app.globalData.ewBluetooth.serviceUuid)

            wx.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                deviceId: did,
                // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
                serviceId: app.globalData.ewBluetooth.serviceUuid, //-----注意是 services[0].uuid
                success: function (res) {
                    app.log('====>>服务信息如下：')
                    app.log(res)
                    getRWN_index(res.characteristics)
                    app.globalData.ewBluetooth.characteristics = res.characteristics
                    // app.log('该设备 第一个服务的 信息: ', app.globalData.ewBluetooth)

                },
                fail: function () {
                    app.log("获取连接设备的所有特征值：", res);
                },
                complete: function () {
                    app.log("获取服务执行完成!获取到的服务信息如下：");
                    app.log(app.globalData.ewBluetooth)

                    var b = false
                    if (app.globalData.ewBluetooth.characteristics[0].uuid != '') {
                        b = true
                    }
                    callback && typeof callback === 'function' ? callback(b) : null;
                }
            })
        }
    })
}

//发送
function sendMsg(str, callback) {
    var timeOut = setTimeout(function () {
        app.log("====>>50")
    }, 50)
    str = str + '\n'
    app.log('====>>数据')
    app.log(str)
    let send_num = Math.ceil(str.length / 20)
    app.log('====>>分包次数：' + send_num)
    let str1 = ''
    let b = false
    for (var i = 0; i < send_num; i++) {
        str1 = str.substr(i * 20, (i + 1) * 20)
        app.log('====>>第 ' + (i + 1) + '次发送：' + str1)
        let buffer = toBuffer(str1, 0)

        wx.writeBLECharacteristicValue({
            deviceId: app.globalData.ewBluetooth.deviceId,
            serviceId: app.globalData.ewBluetooth.serviceUuid,
            characteristicId: app.globalData.ewBluetooth.characteristics[app.globalData.service.w_index].uuid,
            value: buffer,
            success: function (res) {
                app.log('发送 成功', res)
                b = true
            },
            fail: function (err) {
                app.log('====>>发送Str 失败')
                app.log(err)
                // app.globalData.equconn0 = false
            }

        })
    }
    callback && typeof callback === 'function' ? callback(b) : null;


}

function sendHex(str, callback) {
    app.log('==>>发送：' + str)
    app.log(new Date().getTime())
    app.globalData.urs_all = []
    var timeOut = setTimeout(function () {
        app.log("====>>timeout:50")
    }, 50)
    let code = str.split(" ")
    app.log(code)

    let send_num = Math.ceil(code.length / 20)
    app.log('====>>分包次数：' + send_num)
    let str1 = ''
    let b = false

    for (var i = 0; i < send_num; i++) {
        for (let j = i * 20; j < (i + 1) * 20; j++) {
            str1 += code[j]
        }
        str1 = str1.replace(new RegExp('undefined', 'gm'), '')
        app.log('==>>str1:' + str1)
        app.log('====>>第 ' + (i + 1) + '次发送：' + str1)
        let buffer = toBuffer(str1, 16)
        wx.writeBLECharacteristicValue({
            deviceId: app.globalData.ewBluetooth.deviceId,
            serviceId: app.globalData.ewBluetooth.serviceUuid,
            characteristicId: app.globalData.ewBluetooth.characteristics[app.globalData.service.w_index].uuid,
            value: buffer,
            success: function (res) {
                app.log('发送 成功', res)
                b = true
            },
            fail: function (err) {
                app.log('====>>发送Hex 失败')
                app.log(err)
                // app.globalData.equconn0 = false
            }

        })
    }
    callback && typeof callback === 'function' ? callback(b) : null;


}

//接收消息
function readMsg() {
    // // 必须在这里的回调才能获取
    // wx.onBLECharacteristicValueChange(function(characteristic) {
    // 	let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join(
    // 		'');
    // 	app.log('===============hex')
    // 	app.log(hex)
    // })
    if (app.globalData.ewBluetooth.characteristics[app.globalData.service.r_index].properties.read) {
        wx.readBLECharacteristicValue({
            deviceId: app.globalData.ewBluetooth.deviceId,
            serviceId: app.globalData.ewBluetooth.serviceUuid,
            characteristicId: app.globalData.ewBluetooth.characteristics[app.globalData.service.r_index].uuid,
            success: function (res) {
                app.log('读取到的数据:');
                app.log(res)
                app.log(res.errMsg)
            }
        })
    } else {
        app.log('===此服务不可读')
    }
}

//监听蓝牙连接状态
function onBLEState() {
    app.log('==============启用低功耗蓝牙设备特征值变化时的 notify 功能')
    app.log(app.globalData.ewBluetooth)
    wx.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: app.globalData.ewBluetooth.deviceId,
        serviceId: app.globalData.ewBluetooth.serviceUuid,
        characteristicId: app.globalData.ewBluetooth.characteristics[app.globalData.service.n_index].uuid,

        success(res) {
            app.log('==============>>> 监听蓝牙notify 成功')
            app.log(res)
        },
        fail(res) {
            app.log(res, '启用低功耗蓝牙设备监听失败')
        },
        complete(res) {
            /*用来监听手机蓝牙设备的数据变化*/
            app.log('====>>>监听数据变化最终执行')
            app.log(res)
            // wx.onBLEConnectionStateChange(function(res) {
            // 	app.log("监听蓝牙连接状态: " + JSON.stringify(res));
            // 	// 该方法回调中可以用于处理连接意外断开等异常情况
            // 	app.log(`设备： ${res.deviceId}  的连接状态: ${res.connected}`)
            // })


        }
    })


}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}

function ab2Ascii(buffer) {
    var str = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return String.fromCharCode(bit);
        }
    )
    return str.join('');
}

function ab2String(buffer) {
    var str = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return bit.toString();
        }
    )
    return str.join('');
}


function ctof(temp) {

    return changeTwoDecimal_f(((Math.floor((temp * 9 / 5 + 3200) / 10)) / 10));
}

function ftoc(temp) {

    return ((temp - 32) * 5 / 9).toFixed(1);
}

function handleData(temp) {

    return changeTwoDecimal_f(((Math.floor(temp / 10)) / 10))

}

function changeTwoDecimal_f(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
        return 0;
    }
    var f_x = Math.round(x * 100) / 100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 1) {
        s_x += '0';
    }
    return s_x;
}

/*================ 登录验证 ===================*/
// function checkToken() {
//     if (app.globalData.head.token == null || app.globalData.head.token == '') {
//
//         wx.showModal({
//             title: '您还没有登录',
//             content: '授权登录后方可使用小程序所有功能',
//             confirmText: '立即授权',
//             cancelText: '我先看看',
//             showCancel: true,
//             success(res) {
//                 if (res.confirm) {
//                     app.log('====>>token过期，用户点击确定')
//                     wx.navigateTo({
//                         url: '/pages/index/index'
//                     })
//                 } else if (res.cancel) {
//                     app.log('====>>token过期，用户点击取消')
//                 }
//             }
//         })
//     }
// }
function checkbluetooandlocation(callback) {
    let startfind = false
    wx.openBluetoothAdapter({
        success: function (res) {
            if (app.globalData.isA) {
                //定位
                const ress = wx.getSystemInfoSync()
                app.log('====ress')
                app.log(ress)
                if (ress.locationEnabled) {
                    startfind = true

                    app.log('====设备开关检查结果：' + startfind)
                    callback && typeof callback === 'function' ? callback(startfind) : null;

                } else {
                    wx.showToast({
                        title: '定位开启失败,请检查手机定位是否已打开\n操作完成后请重试',
                        icon: 'none',
                        mask: true,
                        duration: 5000
                    })
                    setTimeout(function (res) {
                        wx.navigateBack({
                            delta: 1
                        })
                    }, 4000)
                }
            } else {
                //IOS
                startfind = true

                app.log('====设备开关检查结果：' + startfind)
                callback && typeof callback === 'function' ? callback(startfind) : null;

            }
        },
        fail: function (err) {
            //这里是，手机的蓝牙关闭状态下，该接口会返回10001，执行fail方法
            app.log(err)
            if (err.errCode == 10001) {
                wx.showToast({
                    title: '蓝牙开启失败,请检查手机蓝牙是否已打开\n操作完成后请重试',
                    icon: 'none',
                    mask: true,
                    duration: 5000
                })
            }
        }
    })


}

function reConn() {
    app.log('====>>启动自动重连...')
    let reConnNum = 0

    setInterval(function () {
            if (reConnNum < 2) {
                reConnNum++
                if (!app.globalData.equconn0 && app.globalData.equ != null && app.globalData.equ.name != '') {
                    app.log('====>>自动重连设备')
                    const pages = getCurrentPages();
                    const currentPage = pages[pages.length - 1];
                    const url = `/${currentPage.route}`;
                    if (url == '/pages/lishi/lishi') {

                    } else {
                        checkbluetooandlocation(function (res) {
                            if (res) {
                                connToDid()
                            }
                        })
                    }


                }
            }

        }
        , 10000);
}

function bindBT(name, did, mac) {
    if (name != null && name.length > 0) {
        app.log('====>>绑定设备')
        app.globalData.equ.name = name
        app.globalData.equ.mac = mac

        if (did == null || did == '') {

        } else {
            app.globalData.equ.deviceId = did

        }

        wx.setStorageSync('equ_name', app.globalData.equ.name)
        wx.setStorageSync('equ_did', app.globalData.equ.deviceId)
        wx.setStorageSync('equ_mac', app.globalData.equ.mac)
    }

}

function unbindBT() {
    app.log('====>>解绑设备')
    app.globalData.equs = []
    app.globalData.equ.name = ''
    app.globalData.equ.deviceId = ''
    app.globalData.equ.mac = ''


    wx.removeStorageSync('equ_name')
    wx.removeStorageSync('equ_did')
    wx.removeStorageSync('equ_mac')
}

function getMac(device, callback) {

    app.log('====>>GET MAC')
    app.log(device)
    app.log(device.localName)
    let mac = ''
    const caseInsensitiveRegex = /S+/i;

    if (caseInsensitiveRegex.test(device.localName) || device.localName.length > 0) {
        mac = '00:00'
        if (device.deviceId.toString().length > 0) {
            if (app.globalData.isA) {
                app.log('==>>安卓mac')
                mac = device.deviceId
            }
            if (mac.length < 15 && device.hasOwnProperty("mac")) {
                app.log('==>>IOS mac')
                mac = mac_format(device.mac)
            }
            if (mac.length < 15 && device.hasOwnProperty("advertisData")) {
                let mac0 = ab2hex(device.advertisData).substr(4).toUpperCase()
                app.log('==mac0:' + mac0)
                mac = mac_format(mac0)
            }


        }
        // else if (device.advertisData.toString().length > 0) {
        //     let mac0 = ab2hex(device.advertisData).substr(4).toUpperCase()
        //     mac = mac0.replace(/3A/g, ':')
        //     if (app.globalData.equ.mac == mac) {
        //         app.log('====>>扫码连接设备匹配成功')
        //         app.globalData.equ.deviceId = device.deviceId
        //     }
        // }


    }
    callback && typeof callback === 'function' ? callback(mac) : null;
}

function mac_format(str) {
    return str.replace(/\w(?=(\w{2})+$)/g, "$&:");
}

function getS_index(services) {

    app.globalData.service.s_index = 1

    for (let i in services) {
        if (services[i].uuid.indexOf("FFE0") > -1) {
            app.globalData.service.s_index = i
            break;
        }
    }

}

function getRWN_index(charas) {
    app.globalData.service.r_index = 0
    app.globalData.service.w_index = 0
    app.globalData.service.n_index = 0

    for (let i in charas) {
        if (charas[i].properties.notify == true) {
            app.globalData.service.n_index = i
        }
        if (charas[i].properties.write == true) {
            app.globalData.service.w_index = i
        }
    }

}

function toBuffer(str, type) {
    app.log('==>>发送数据')
    app.log(str)

    let buffer = new ArrayBuffer(str.length)
    switch (type) {
        case 0:
            let dataView = new DataView(buffer)
            for (var j = 0; j < str.length; j++) {
                dataView.setUint8(j, str.charAt(j).charCodeAt())
            }
            break
        case 16:
            var typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
                return parseInt(h, 16)
            }))
            app.log(typedArray)
            buffer = typedArray.buffer
            break
    }

    app.log(buffer)
    return buffer;
}


function getSn(type) {
    app.globalData.SEND_NUM
    app.log('====设备确认')
    app.log('==>>BLE_SN:' + app.globalData.BLE_SN)
    app.log(app.globalData.SEND_NUM)

    let str = ''
    if (app.globalData.equconn0 && app.globalData.BLE_SN == 100) {

        if (app.globalData.SEND_NUM == 12) {
            wx.showModal({
                title: '设备识别失败',
                content: '设备自动识别失败，请重试。',
                success(res) {
                    if (res.confirm) {
                        app.log('用户点击确定')
                        // app.globalData.BLE_SN = 701
                    } else if (res.cancel) {
                        app.log('用户点击取消')
                    }
                    stopBind()
                }
            })

            // app.globalData.BLE_SN = 701
        }
        app.globalData.SEND_NUM++
        if (app.globalData.SEND_NUM < 10) {
            switch (type) {
                case 0:
                    str = 'UIH' //获取SN
                    utilBT.sendMsg(str)
                    break
                case 16:
                    if (app.globalData.SEND_NUM == 2 | app.globalData.SEND_NUM == 6) {
                        str = '93 8E 08 00 08 01 43 4F 4E 54 45' //设备确认
                    } else if (app.globalData.SEND_NUM == 3 || app.globalData.SEND_NUM == 7) {

                        str = '93 8E 04 00 08 0E 1A'

                    } else {
                        str = '55 49 48'
                    }
                    sendHex(str)
                    break
            }
        }

    }

}

function stopBind() {
    closeconn(app.globalData.equ.deviceId)
    unbindBT()

    wx.navigateBack({
        delta: 1
    })
}